import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../../../utils/logger_util.dart';
import '../../../data/chat/action_type.dart';
import '../../../data/chat/message.dart';
import '../../../services/websocket_service_2.dart';

class Chat2Controller extends GetxController {
  var editTextController = TextEditingController();
  var urlEditTextController = TextEditingController();
  var tokenEditTextController = TextEditingController();

  final messageList = <Message>[].obs;
  final inputText = ''.obs;

  static const defaultUrl = 'ws://124.222.6.60:8800';

  // static const defaultUrl = 'ws://192.168.1.183:8090/ws';
  static const token = '';

  @override
  void onInit() {
    super.onInit();
    editTextController.addListener(() {});
    Get.put(WebSocketService2());

    // _connectWebsocket();
  }

  @override
  void onReady() {
    super.onReady();

    updateUrlInputText(defaultUrl);
  }

  @override
  void onClose() {
    _disconnectWebsocket();
    super.onClose();
  }

  void updateInputText(String text) {
    editTextController.text = text;
  }

  void cleanInputText() {
    editTextController.clear();
  }

  void updateUrlInputText(String text) {
    urlEditTextController.text = text;
  }

  void cleanUrlInputText() {
    urlEditTextController.clear();
  }

  void updateTokenInputText(String text) {
    tokenEditTextController.text = text;
  }

  void cleanTokenInputText() {
    tokenEditTextController.clear();
  }

  void handlerMessage() {}

  void connectWebsocket() {
    _connectWebsocket();
  }

  void _connectWebsocket() async {
    Message message = Message(
      content: '开始连接,请稍等...',
      timestamp: DateTime.now().toString(),
    );
    _addMessage(message);

    final url =
        urlEditTextController.text.isEmpty
            ? defaultUrl
            : urlEditTextController.text;

    logE('_connectWebsocket url:$url');

    await WebSocketService2.to.connect(url, token);

    if (WebSocketService2.to.isConnected.value) {
      Message connectedMessage = Message(
        content: '已连接',
        timestamp: DateTime.now().toString(),
      );

      _addMessage(connectedMessage);
    }

    _setupWebSocket();
  }

  void disconnectWebsocket() {
    _disconnectWebsocket();
  }

  void _disconnectWebsocket() {
    WebSocketService2.to.disconnect();

    Message message = Message(
      content: '连接已断开',
      timestamp: DateTime.now().toString(),
    );
    _addMessage(message);
  }

  void _setupWebSocket() {
    WebSocketService2.to.stream.listen(
      (data) {
        logE('_setupWebSocket()-->data:$data');

        // Message message = Message.fromJson(data);
        Message msg = Message(
          content: data,
          timestamp: DateTime.now.toString(),
          actionType: ActionType.receive,
        );

        _addMessage(msg);
      },
      onDone: () => _disconnectWebsocket(),
      onError: (err) {
        logE('_setupWebSocket()-->onError:$err');
      },
    );
  }

  void _addMessage(Message message) {
    messageList.insert(0, message);
  }

  void sendMessage(String text) {
    if (text.isEmpty) {
      return;
    }

    Message message = Message(
      content: text,
      timestamp: DateTime.now().toString(),
      actionType: ActionType.send,
    );

    // WebSocketService.to.sendMessage(message);
    WebSocketService2.to.sendMessage(text);

    _addMessage(message);

    editTextController.clear();
  }
}
